package Services

import (
	"database/sql"
	"errors"
	"golang.org/x/crypto/bcrypt"
	"minititok/Entities"
	"minititok/databases"
)

func HashPassword(raw string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.DefaultCost)
	return string(bytes), err
}

func CheckPassword(raw string, hashed string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hashed), []byte(raw))
	return err == nil
}

func RegisterUser(user *Entities.User) error {
	// 校验用户名重复
	var existing Entities.User
	if err := databases.DB.Where("username = ?", user.Username).First(&existing).Error; err == nil {
		return errors.New("username already exists")
	}

	// 密码加密
	hashedPwd, err := HashPassword(user.Password)
	if err != nil {
		return err
	}
	user.Password = hashedPwd

	// 分配UID (例如自增最大+1或用雪花算法)
	var maxUID sql.NullInt64
	databases.DB.Model(&Entities.User{}).Select("MAX(uid)").Scan(&maxUID)
	if maxUID.Valid {
		user.UID = int(maxUID.Int64 + 1)
	}

	return databases.DB.Create(user).Error
}

func FindUserByUsername(username string) (*Entities.User, error) {
	var user Entities.User
	if err := databases.DB.Where("username = ?", username).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func FindUserByUID(uid int) (*Entities.User, error) {
	var user Entities.User
	if err := databases.DB.Where("uid = ?", uid).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func UpdateAvatar(user *Entities.User) error {
	result := databases.DB.Model(user).Select("avatar").Where("uid = ?", user.UID).Update("avatar", user.Avatar)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("用户记录不存在或未更改")
	}

	return nil
}
